package com.enterprise.support.utility.captcha;

import com.google.code.kaptcha.text.WordRenderer;
import com.google.code.kaptcha.util.Configurable;

import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: Zhanggaojiang
 * Date: 11-1-19
 * Time: 上午10:20
 * Email: z82422@gmail.com
 * 漂亮的 图形验证码
 */
public class VerifyWordRenderer extends Configurable implements WordRenderer {
    public VerifyWordRenderer() {
    }

    public BufferedImage renderWord(String word, int width, int height) {
        int fontSize = getConfig().getTextProducerFontSize();
        Font fonts[] = getConfig().getTextProducerFonts(fontSize);
        java.awt.Color color = getConfig().getTextProducerFontColor();
        BufferedImage image = new BufferedImage(width, height, 2);
        Graphics2D g2D = image.createGraphics();
        g2D.setColor(color);
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
        g2D.setRenderingHints(hints);

        FontRenderContext frc = g2D.getFontRenderContext();
        Random random = new Random();
        int startPosX = width / (word.length()) - 9;

        char wordChars[] = word.toCharArray();
        for (int i = 0; i < wordChars.length; i++) {
            Font chosenFont = fonts[random.nextInt(fonts.length)];
            g2D.setFont(chosenFont);
            char charToDraw[] = {wordChars[i]};
            GlyphVector gv = chosenFont.createGlyphVector(frc, charToDraw);
            double charWidth = gv.getVisualBounds().getWidth() + 4;
            //g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, 20);
            g2D.drawString(String.valueOf(wordChars[i]), startPosX, 20);
            startPosX += 15;//(int) charWidth;
        }
        return image;
    }

}
